#include "func.h"
#include "cmdHandler.h"
#include "transFile.h"
#include "dircmd.h"
#include "dircmd2_sql.h"
#include "cmd_mysql.h"
int getCmdType(const cmd_t *pCmdInfo) {
    if(strcmp(pCmdInfo->cmd, "cd") == 0) {
        return CD;
    } else if(strcmp(pCmdInfo->cmd, "ls") == 0) {
        return LS;
    } else if(strcmp(pCmdInfo->cmd, "pwd") == 0) {
        return PWD;
    } else if(strcmp(pCmdInfo->cmd, "puts") == 0) {
        return PUTS;
    } else if(strcmp(pCmdInfo->cmd, "gets") == 0) {
        return GETS;
    } else if(strcmp(pCmdInfo->cmd, "rm") == 0) {
        return RM;
    } else if(strcmp(pCmdInfo->cmd, "rmdir") == 0) {
        return RMDIR;
    } else if(strcmp(pCmdInfo->cmd, "mkdir") == 0) {
        return MKDIR;
    } else {
        return -1;
    }
}

int handleCmd(const int netfd, const train_t *pTrain, dirStack_t *pStack, MYSQL *connect, char *username) {
    cmd_t cmdInfo;
    memcpy(&cmdInfo, pTrain->data, pTrain->length);

    int cmdType = getCmdType(&cmdInfo);
    if(cmdType == -1) {
        return -1;
    }

    char buf[1024] = {0};
    train_t train;
    
    switch(cmdType) {
    case CD:
        bzero(buf, sizeof(buf));
        //mycd(pStack, cmdInfo.args, buf);
        printf("cd test 45\n");
        cd_mysql(username,pStack,cmdInfo.args,connect,buf);

        bzero(&train, sizeof(train_t));
        train.length = strlen(buf);
        memcpy(train.data, buf, train.length);
        send_msg(netfd, &train);
        break;
    case LS:
        bzero(buf, sizeof(buf));
        //myls(pStack, cmdInfo.args, buf);
        ls_mysql(pStack,connect,buf);
        printf("ls test 57 buf = %s\n",buf);
        train.length = strlen(buf);
        memcpy(train.data, buf, train.length);
        send_msg(netfd, &train);
        break;
    case PWD:
        bzero(buf, sizeof(buf));
        //mypwd(pStack, buf);
        pwd_mysql(pStack,username,connect,buf);
        printf("pwd test 66 : %s\n",buf);
        train.length = strlen(buf);
        memcpy(train.data, buf, train.length);
        send_msg(netfd, &train);
        break;
    case PUTS:
        transFile(netfd, RECVF, pStack, connect,  username);
        break;
    case GETS:
        transFile(netfd, SENDF, pStack, connect, username);
        break;
    case RM:
        myRm(netfd, pStack, cmdInfo.args, username, connect);
        break;
    case RMDIR:
        myRmdir(netfd, pStack, cmdInfo.args, username, connect);
        break;
    case MKDIR:
        myMkdir(netfd, pStack, cmdInfo.args, username, connect);
        break;
    default:
        break;
    }
    return 0;
}
